package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.pojo.dto.UserAuthorizationPageDTO;
import com.xbongbong.paas.pojo.dto.UserAuthorizationSaveDTO;
import com.xbongbong.paas.pojo.vo.UserAuthorizationPageDataVO;
import com.xbongbong.paas.pojo.vo.UserAuthorizationPageVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.CommentUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.domain.entity.UserAuthorizationEntity;
import com.xbongbong.saas.model.UserAuthorizationModel;
import com.xbongbong.saas.service.UserAuthorizationService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author WuHB
 * @date 2022/08/30 15:31
 */
@Service("userAuthorizationService")
public class UserAuthorizationServiceImpl implements UserAuthorizationService {

    @Resource
    private UserAuthorizationModel userAuthorizationModel;

    /**
     * 用户授权信息保存
     *
     * @param saveDto 保存类
     * @return 影响行数
     * @throws XbbException 异常
     */
    @Override
    public Integer save(UserAuthorizationSaveDTO saveDto) throws XbbException {
        UserAuthorizationEntity entity = getBase64Code(saveDto.getData());
        entity.setCorpid(saveDto.getCorpid());
        return userAuthorizationModel.insert(entity);
    }

    /**
     * 分页查询
     *
     * @param pageDto 分页条件
     * @return 分页信息
     * @throws XbbException 异常
     */
    @Override
    public UserAuthorizationPageVO page(UserAuthorizationPageDTO pageDto) throws XbbException {
        Map<String, Object> pageParam = getPageParam(pageDto);
        Integer total = userAuthorizationModel.getEntitysCount(pageParam);
        List<UserAuthorizationPageDataVO> dataList = new ArrayList<>();
        if (total > 0) {
            List<UserAuthorizationEntity> entityList = userAuthorizationModel.findEntitys(pageParam);
            dataList = entityList.stream().map(entity -> {
                UserAuthorizationPageDataVO pageDataVO = new UserAuthorizationPageDataVO();
                BeanUtils.copyProperties(entity, pageDataVO);
                return pageDataVO;
            }).collect(Collectors.toList());
        }
        PageHelper pageHelper = new PageHelper();
        pageHelper.setRowsCount(total);
        pageHelper.setCurrentPageNum(pageDto.getPage());
        pageHelper.setPageSize(pageDto.getPageSize());
        UserAuthorizationPageVO pageVO = new UserAuthorizationPageVO();
        pageVO.setPageHelper(pageHelper);
        pageVO.setData(dataList);
        return pageVO;
    }

    /**
     * 获取base64解码后的用户授权信息
     *
     * @param data base64编码的字符串
     * @return 用户授权信息
     */
    private UserAuthorizationEntity getBase64Code(String data) throws XbbException {
        byte[] decode = Base64.getDecoder().decode(data.getBytes(StandardCharsets.UTF_8));
        String jsonData = new String(decode);
        UserAuthorizationEntity entity = JSONObject.parseObject(jsonData, UserAuthorizationEntity.class);
        if (StringUtil.isNotEmpty(entity.getProblemDescription()) && entity.getProblemDescription().length() > 1000) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, ErrorMessageConstant.DESCRIPTION_LENGTH_OVER_LIMIT);
        }
        long now = DateTimeUtil.getInt();
        entity.setAuthorizationTime(now);
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        entity.setDel(DelEnum.NORMAL.getDel());
        return entity;
    }

    /**
     * 获取分页的查询条件
     *
     * @param pageDto 分页条件
     * @return 查询条件
     */
    private Map<String, Object> getPageParam(UserAuthorizationPageDTO pageDto) {
        Map<String, Object> param = new HashMap<>();
        param.put("start", (pageDto.getPage() - 1) * pageDto.getPageSize());
        param.put("pageNum", pageDto.getPageSize());
        CommentUtil.addToMap(param, "corpid", pageDto.getQueryCorpid());
        CommentUtil.addToMap(param, "numberLike", pageDto.getCorpNameLike());
        CommentUtil.addToMap(param, "userId", pageDto.getQueryUserId());
        return param;
    }
}
